import * as React from 'react';
import { Form, Input, Modal, Select, message } from 'antd';
import request from '@/http';
import './addClass.less';
import { useState } from 'react';
import qs from 'qs';
import { loginUser } from '@/pages/login/cookie';

const { Option } = Select;

interface UserEditObject {
  isModalVisible: boolean;
  disAble: boolean;
  id?: number;
  collegesName?: string;
  collegesId?: number;
  majorId?: number;
  majorName?: string;
  gradeInfoId?: number;
  gradeName?: string;
  className?: string;
  classBaseInfoId?: number;
  classId?: number;
  classTeacher?: string;
  teacherId?: number;
  isGraduation?: number;
  studentTotal?: number;
}

//学生信息管理  （新增）  （编辑）
const SAddEdit = (props: { editObject: UserEditObject; onClose: any }) => {
  const { editObject, onClose } = props;
  const newEditObject = {
    ...editObject,
  };
  console.log(newEditObject);

  // console.log(editObject);
  const [isModalVisible, setIsModalVisible] = React.useState(false);

  const [disAble, setDisAble] = React.useState(false);
  const [formObject] = Form.useForm();
  //从web存储中读取数据
  let cCollege = localStorage.getItem('collegesName');
  if (cCollege != null) {
    var cCollegeData = JSON.parse(cCollege);
  }
  const cGrade = localStorage.getItem('gradeName');
  if (cGrade != null) {
    var cGradeData = JSON.parse(cGrade);
  }
  let cClass = localStorage.getItem('classname');
  if (cClass != null) {
    var cClassData = JSON.parse(cClass);
  }
  let cTeacher = localStorage.getItem('teacher');
  if (cTeacher != null) {
    var cTeacherData = JSON.parse(cTeacher);
  }

  const [maj, setMaj] = React.useState([]);
  const getMajor = async () => {
    const data = formObject.getFieldsValue();
    console.log(data);
    console.log(data.collegeName);
    const ds = {
      collegeId: data.collegeName,
    };
    const chooseMajor: any = await request.post(
      '/api/common_module/a_t_s/getMajor',
      qs.stringify(ds),
    );

    console.log(chooseMajor);
    const cMajor = chooseMajor.data.map((user: any) => ({
      key: `user_${user.majorId}`,
      id: user.majorId,
      majorId: user.majorId,
      majorName: user.majorName,
    }));

    // console.log(cMajor);

    setMaj(cMajor);
  };

  const [] = React.useState();
  const [secondCity, setSecondCity] = React.useState(maj[0]);

  console.log(maj[0]);

  const handleProvinceChange = (value: any) => {
    console.log(value);
    getMajor();
    // @ts-ignore
    setSecondCity((value = ''));
  };

  const onSecondCityChange = (value: any) => {
    setSecondCity(value);
  };

  const modelOnOk = async () => {
    if (flag) {
      // 有id  编辑班级信息
      const data = await formObject.validateFields();
      console.log('编辑班级信息：（1)', editObject.id);

      console.log('编辑班级信息：（2)', data);
      console.log(newEditObject.teacherId);
      console.log(newEditObject.majorId);
      //序列化
      let dataStr = '';
      const ds = {
        ...data,
        id: editObject.id,
        collegesId:
          data.collegeId == undefined
            ? newEditObject.collegesId
            : data.collegeId,
        gradeInfoId:
          data.gradeInfoId == undefined
            ? newEditObject.gradeInfoId
            : data.gradeInfoId,
        majorId: data.majorId ? data.majorId : newEditObject.majorId,
        teacherId: data.teacherId ? data.teacherId : newEditObject.teacherId,
        isGraduation: data.isGraduation == '0' ? 0 : 1,
        classBaseInfoId: data.classId
          ? data.classId
          : newEditObject.classBaseInfoId,
      };
      console.log('编辑班级信息ds:', ds);
      for (let i in ds) {
        if (dataStr != '') dataStr += '&';
        dataStr += encodeURIComponent(i) + '=' + encodeURIComponent(ds[i]);
      }
      // console.log('更改编辑班级信息：（3)', dataStr);

      const result: any = await request.post(
        '/api/admin/studentInfoManagement/editClass',
        dataStr,
      );
      console.log('编辑班级结果：', result);
      if (result.code == 200) {
        setTimeout(() => {
          message.success('修改成功');
        }, 200);
        setIsModalVisible(false);
      }
      console.log(123);
      if (result.code == 400) {
        setTimeout(() => {
          message.success('已存在相同班级信息');
        }, 200);
      }
    } else {
      //flag: false   新增班级
      const data = await formObject.validateFields();

      const ds = {
        ...data,
        collegesId: data.collegeName,
        gradeInfoId: data.gradeName,
        majorId: data.majorName,
        teacherId: data.teacherId,
        classBaseInfoId: data.className,
        isGraduation: data.isGraduation == '0' ? 0 : 1,
      };
      console.log(ds);

      const result: any = await request.post(
        '/api/admin/studentInfoManagement/insertClass',
        qs.stringify(ds),
      );
      console.log('新增班级：', result);
      if (result.code == 200) {
        setTimeout(() => {
          message.success('添加成功');
        }, 200);

        if (onClose) {
          onClose();
        }
        setIsModalVisible(false);
      }
    }
  };

  const modelOnCancel = () => {
    setIsModalVisible(false);
  };

  //从当前列表获取数据
  React.useEffect(() => {
    setIsModalVisible(editObject.isModalVisible);
    if (editObject.id !== null) {
      formObject.setFieldsValue({
        collegeName: editObject.collegesName,
        collegeId: editObject.collegesId,
        majorName: editObject.majorName,
        majorId: editObject.majorName,
        gradeName: editObject.gradeName,
        className: editObject.className,
        classTeacher: editObject.classTeacher,
        teacherId: editObject.teacherId,
        isGraduation: editObject.isGraduation == 1 ? '已结业' : '未结业',
      });
    }
  }, [editObject]);

  //有id为真 编辑班级信息
  const flag = editObject.id !== null && editObject.id !== undefined;

  return (
    <>
      <Modal
        width={1200}
        className="modal"
        title={flag ? '编辑班级信息' : '新增班级'}
        visible={isModalVisible}
        onCancel={modelOnCancel}
        onOk={modelOnOk}
        maskClosable={false}
        destroyOnClose
        okText="确认"
        cancelText="取消"
        getContainer={false}
      >
        <Form
          className="form"
          name="editForm"
          form={formObject}
          preserve={false}
        >
          <Form.Item label="院系" name="collegeName" initialValue="">
            <Select
              defaultValue={cCollegeData[0].collegeName}
              className="studentSelect adds"
              onChange={handleProvinceChange}
            >
              <Option value="">请选择...</Option>
              {cCollegeData
                ? cCollegeData.map((item: any, index: number) => (
                    <Option key={index} value={item.collegeId}>
                      {item.collegeName}
                    </Option>
                  ))
                : ''}
            </Select>
          </Form.Item>
          <Form.Item
            label="专&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;业"
            name="majorName"
            initialValue=""
          >
            <Select
              className="studentSelect adds"
              disabled={disAble}
              value={secondCity}
              onChange={onSecondCityChange}
            >
              <Option value="">请选择...</Option>
              {maj
                ? maj.map((item: any, index: number) => (
                    <Option key={index} value={item.majorId}>
                      {item.majorName}
                    </Option>
                  ))
                : ''}
            </Select>
          </Form.Item>
          <Form.Item></Form.Item>
          <Form.Item
            label="年&nbsp;&nbsp;&nbsp;&nbsp;级"
            name="gradeName"
            initialValue=""
          >
            <Select className="studentSelect adds">
              <Option value="">请选择...</Option>
              {cGradeData
                ? cGradeData.map((item: any, index: any) => {
                    return (
                      <Option
                        index={index}
                        key={index}
                        value={item.gradeId}
                        children={item.gradeName}
                      />
                    );
                  })
                : ''}
            </Select>
          </Form.Item>
          <Form.Item label="班级" name="className" initialValue="">
            <Select className="studentSelect adds">
              <Option value="">请选择...</Option>
              {cClassData
                ? cClassData.map((item: any, index: any) => {
                    return (
                      <Option
                        index={index}
                        key={index}
                        value={item.classId}
                        children={item.className}
                      />
                    );
                  })
                : ''}
            </Select>
          </Form.Item>
          <Form.Item label="是否结业" name="isGraduation" initialValue="">
            <Select className="studentSelect adds">
              <Option value="">请选择...</Option>
              <Option value="1">已结业</Option>
              <Option value="0">未结业</Option>
            </Select>
          </Form.Item>

          <Form.Item label="班主任" name="teacherId" initialValue="">
            <Select className="studentSelect adds">
              <Option value="">请选择...</Option>
              {cTeacherData
                ? cTeacherData.map((item: any, index: any) => {
                    return (
                      <Option
                        index={index}
                        key={index}
                        value={item.teacherId}
                        children={item.teacherName}
                      />
                    );
                  })
                : ''}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export { SAddEdit, UserEditObject };
